package com.example.demo.controller;

import com.example.demo.dto.ApiResponse;
import com.example.demo.dto.CreateOrderRequest;
import com.example.demo.dto.OrderDTO;
import com.example.demo.service.OrderService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * Order Controller
 * 
 * REST API endpoints for order management
 */
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
@Slf4j
public class OrderController {

    private final OrderService orderService;

    /**
     * Get all orders
     * 
     * @return List of all orders
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<OrderDTO>>> getAllOrders() {
        log.info("GET /api/orders - Fetching all orders");
        List<OrderDTO> orders = orderService.getAllOrders();
        return ResponseEntity.ok(ApiResponse.success("Orders retrieved successfully", orders));
    }

    /**
     * Get order by ID
     * 
     * @param id Order ID
     * @return Order details
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<OrderDTO>> getOrderById(@PathVariable Long id) {
        log.info("GET /api/orders/{} - Fetching order by ID", id);
        try {
            OrderDTO order = orderService.getOrderById(id);
            return ResponseEntity.ok(ApiResponse.success("Order retrieved successfully", order));
        } catch (RuntimeException e) {
            log.error("Error fetching order with ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * Get orders by user ID
     * 
     * @param userId User ID
     * @return List of user's orders
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<ApiResponse<List<OrderDTO>>> getOrdersByUserId(@PathVariable Long userId) {
        log.info("GET /api/orders/user/{} - Fetching orders by user ID", userId);
        try {
            List<OrderDTO> orders = orderService.getOrdersByUserId(userId);
            return ResponseEntity.ok(ApiResponse.success("User orders retrieved successfully", orders));
        } catch (RuntimeException e) {
            log.error("Error fetching orders for user ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * Create new order
     * 
     * @param request Create order request
     * @return Created order
     */
    @PostMapping
    public ResponseEntity<ApiResponse<OrderDTO>> createOrder(@Valid @RequestBody CreateOrderRequest request) {
        log.info("POST /api/orders - Creating new order for user ID: {}", request.getUserId());
        try {
            OrderDTO order = orderService.createOrder(request);
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ApiResponse.success("Order created successfully", order));
        } catch (RuntimeException e) {
            log.error("Error creating order", e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * Complete order
     * 
     * @param id Order ID
     * @return Updated order
     */
    @PostMapping("/{id}/complete")
    public ResponseEntity<ApiResponse<OrderDTO>> completeOrder(@PathVariable Long id) {
        log.info("POST /api/orders/{}/complete - Completing order", id);
        try {
            OrderDTO order = orderService.completeOrder(id);
            return ResponseEntity.ok(ApiResponse.success("Order completed successfully", order));
        } catch (RuntimeException e) {
            log.error("Error completing order with ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * Cancel order
     * 
     * @param id Order ID
     * @return Updated order
     */
    @PostMapping("/{id}/cancel")
    public ResponseEntity<ApiResponse<OrderDTO>> cancelOrder(@PathVariable Long id) {
        log.info("POST /api/orders/{}/cancel - Cancelling order", id);
        try {
            OrderDTO order = orderService.cancelOrder(id);
            return ResponseEntity.ok(ApiResponse.success("Order cancelled successfully", order));
        } catch (RuntimeException e) {
            log.error("Error cancelling order with ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * Get total revenue
     * 
     * @return Total revenue from completed orders
     */
    @GetMapping("/revenue")
    public ResponseEntity<ApiResponse<BigDecimal>> getTotalRevenue() {
        log.info("GET /api/orders/revenue - Calculating total revenue");
        BigDecimal revenue = orderService.getTotalRevenue();
        return ResponseEntity.ok(ApiResponse.success("Total revenue calculated", revenue));
    }
}

